const jwt = require("jsonwebtoken");
const User = require("@models/user");

const SECRET_KEY = process.env.SECRET_KEY;

// JWT验证中间件
const authenticateToken = async (req, res, next) => {
  try {
    // 从请求头获取token
    const authHeader = req.headers["authorization"];
    const token = authHeader && authHeader.split(" ")[1]; // Bearer TOKEN

    if (!token) {
      return res.status(200).json({
        success: false,
        message: "请重新登陆",
      });
    }

    // 验证token
    const decoded = jwt.verify(token, SECRET_KEY);

    // 查找用户
    const user = await User.findById(decoded.id);
    if (!user) {
      return res.status(200).json({
        success: false,
        message: "用户不存在",
      });
    }

    // 将用户信息添加到请求对象
    req.user = user;
    next();
  } catch (error) {
    if (error.name === "JsonWebTokenError") {
      return res.status(200).json({
        success: false,
        message: "无效的访问令牌",
      });
    }
    if (error.name === "TokenExpiredError") {
      return res.status(200).json({
        success: false,
        message: "访问令牌已过期",
        code: "TOKEN_EXPIRED",
      });
    }
    return res.status(500).json({
      success: false,
      message: "服务器错误",
    });
  }
};

module.exports = authenticateToken;
